<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="55vw" fullscreen>
    <el-form size="large" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">
      <el-row :gutter="24">
        <el-col :span="20">
          <el-form-item label="IP地址" prop="hostName">
            <el-input v-model="formData.hostName" placeholder="请输入IP地址" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="设备类型" prop="deviceType">
            <el-tree-select v-model="formData.deviceType" :data="typeList" :props="defaultPropsType" check-strictly
              node-key="id" placeholder="请选择设备类型" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="业务类型" prop="businessType">
            <el-input v-model="formData.businessType" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="区域" prop="area">
            <el-tree-select v-model="formData.area" :data="areaList" :props="defaultProps" check-strictly node-key="id"
              placeholder="请选择归属区域" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="厂商" prop="manufacturer">
            <el-input v-model="formData.manufacturer" placeholder="请输入厂商" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="型号" prop="model">
            <el-input v-model="formData.model" placeholder="请输入型号" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="序列号" prop="serial">
            <el-input v-model="formData.serial" placeholder="请输入序列号" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="生产日期" prop="manufactureDate">
            <el-date-picker v-model="formData.manufactureDate" type="date" value-format="YYYY-MM-DD"
              placeholder="选择生产日期" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="质保到期日期" prop="warrantyDate">
            <el-date-picker v-model="formData.warrantyDate" type="date" value-format="YYYY-MM-DD"
              placeholder="选择质保到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="设备分布位置" prop="location">
            <el-input v-model="formData.location" placeholder="请输入设备分布位置" />
          </el-form-item>
        </el-col>

        <el-divider content-position="left">详细配置</el-divider>

        <el-col :span="10">
          <el-form-item label="系统名称" prop="sysName">
            <el-input v-model="formData.libreDevice.sysName" placeholder="请输入名称" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="SNMP版本" prop="snmpver">
            <el-select v-model="formData.libreDevice.snmpver" placeholder="请选择SNMP版本" style="width: 100%">
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.SNMP_VERSION)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="端口" prop="port">
            <el-input v-model="formData.libreDevice.port" placeholder="请输入端口" />
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="协议" prop="transport">
            <el-select v-model="formData.libreDevice.transport" placeholder="请选择" style="width: 100%">
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.PROTOCOL_TYPE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="端口关联模式" prop="portAssociationMode">
            <el-select v-model="formData.libreDevice.portAssociationMode" placeholder="请选择" style="width: 100%">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASSOCIATION_TYPE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="!showViews.isV3">
          <el-form-item label="密码" prop="sysName">
            <el-tooltip content="该设备或者服务器密码" effect="customized" placement="top">
              <el-input type="password" v-model="formData.libreDevice.community" placeholder="请输入" />
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="SNMP服务" prop="snmpDisable">
            <el-radio-group v-model="formData.libreDevice.snmpDisable" size="large" fill="#6cf">
              <el-radio-button v-for="item in getIntDictOptions(DICT_TYPE.ENABLED_SNMP)" :key="item.value"
                :value="item.value" :label="item.label" />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="showViews.hardware">
          <el-form-item label="硬件" prop="hardware">
            <el-input v-model="formData.libreDevice.hardware" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="4" v-if="formType == 'create'">
          <el-form-item label="强制添加" prop="force_add">
            <el-tooltip content="选择是则跳过所有检查,将设备添加到数据库" effect="customized" placement="top">
              <el-radio-group v-model="formData.libreDevice.force_add" fill="#6cf">
                <el-radio-button v-for="item in getIntDictOptions(DICT_TYPE.FORCE_ADD)" :key="item.value"
                  :value="item.value" :label="item.label" />
              </el-radio-group>
            </el-tooltip>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="加入监控" prop="pass">
            <el-radio-group v-model="formData.libreDevice.disabled" fill="#6cf">
              <el-radio-button v-for="item in getIntDictOptions(DICT_TYPE.WATCH_TYPE)" :key="item.value"
                :value="item.value" :label="item.label" />
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="showViews.isV3">
          <el-form-item label="身份验证级别" prop="authlevel">
            <el-select v-model="formData.libreDevice.authlevel" placeholder="请选择" style="width: 100%">
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.AUTHLEVEL_TYPE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="showViews.isV3">
          <el-form-item label="身份验证用户名" prop="authname">
            <el-input v-model="formData.libreDevice.authname" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="showViews.isV3">
          <el-form-item label="身份验证密码" prop="authpass">
            <el-input type="password" show-password v-model="formData.libreDevice.authpass" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="showViews.isV3">
          <el-form-item label="身份验证算法" prop="authalgo">
            <el-select v-model="formData.libreDevice.authalgo" placeholder="请选择" style="width: 100%">
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.AUTHALGO_TYPE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10" v-if="showViews.isV3">
          <el-form-item label="加密密码" prop="sysName">
            <el-input type="password" show-password v-model="formData.libreDevice.cryptopass" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { CompanypropertyApi, Companyproperty } from '@/api/business/companyproperty'
import { ElTree } from 'element-plus'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { CompanyAreaApi, CompanyArea } from '@/api/business/localCompanyArea'
import { CompanyDeviceTypeApi, CompanyDeviceType } from '@/api/business/localCompanyDevicetType'
import { getIntDictOptions, getIntDictOptionsString, DICT_TYPE } from '@/utils/dict'
import { computed } from 'vue'
/** 资产 表单 */
defineOptions({ name: 'CompanypropertyForm' })

// 关键：保留原有配置，并添加 isDisabled
const defaultPropsType = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf', // 用于识别叶子节点
  emitPath: false,
  disabled: (data, node) => {
    // 方法 1：根据 children 判断（有 children 就是父节点）
    // return !!(node.children && node.children.length > 0)

    // 方法 2：根据 leaf 字段判断（更推荐，如果你的数据有 leaf 标志）
    // return !data.leaf
    return data.parentId == 0
  }
}

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  hostName: undefined,
  name: undefined,
  deviceType: undefined,
  businessType: undefined,
  area: undefined,
  manufacturer: undefined,
  model: undefined,
  serial: undefined,
  manufactureDate: undefined,
  warrantyDate: undefined,
  location: undefined,
  libreDevice: {
    hostname: '', //IP地址
    sysName: '', //系统名称
    snmpDisable: 0, //SNMP服务 0为启用，其他为禁用
    portAssociationMode: 1, //默认1  ifIndex
    snmpver: 'v2c', //数据库默认是 v2c
    transport: 'udp',
    community: '', //SNMP v1 或 v2c 凭据：SNMP v1 或 v2c 必需。
    port: 161, //默认是161
    force_add: 1, //是否强制添加 0否 其他值为是
    disabled: 0, //0为启用 其他为禁用
    authlevel: '', //身份验证级别
    authname: '', //身份验证用户名
    authpass: '', //身份验证密码
    authalgo: '', //身份验证算法
    cryptopass: '', //加密密码
    cryptoalg: '', //加密算法
    hardware: '' //硬件
  }
})

//动态返回显示或隐藏的列
const showViews = computed(() => {
  const data = formData.value?.libreDevice

  if (!data) return {}

  const { snmpDisable: snmpDisable, snmpver } = data

  //snmp禁用 只显示硬件
  if (snmpDisable == 1) {
    return {
      hardware: true,
      snmpDisable: false,
      isV3: false
    }
  }

  const isV3 = snmpver === 'v3'

  return {
    hardware: false,
    snmpDisable: true,
    isV3: isV3
  }
})

const formRules = reactive({
  hostName: [{ required: true, message: 'IP地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const areaList = ref<Tree[]>([]) // 树形结构

const typeList = ref<Tree[]>([]) // 树形结构

/** 获得部门树 */
const getTypeTree = async () => {
  const res = await CompanyDeviceTypeApi.getCompanyDeviceTypeList(null)
  typeList.value = []
  typeList.value.push(...handleTree(res))
}

/** 获得部门树 */
const getTree = async () => {
  const res = await CompanyAreaApi.getCompanyAreaList(null)
  areaList.value = []
  areaList.value.push(...handleTree(res))
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await getTree()
  await getTypeTree()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CompanypropertyApi.getCompanyproperty(id)

      //设备底座信息
      formData.value.libreDevice
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Companyproperty
    if (formType.value === 'create') {
      await CompanypropertyApi.createCompanyproperty(data)
      message.success(t('common.createSuccess'))
    } else {
      await CompanypropertyApi.updateCompanyproperty(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    hostName: undefined,
    name: undefined,
    deviceType: undefined,
    businessType: undefined,
    area: undefined,
    manufacturer: undefined,
    model: undefined,
    serial: undefined,
    manufactureDate: undefined,
    warrantyDate: undefined,
    location: undefined,
    libreDevice: {
      hostname: '', //IP地址
      sysName: '', //系统名称
      snmpDisable: 0, //SNMP服务 0为启用，其他为禁用
      portAssociationMode: 1, //默认1  ifIndex
      snmpver: 'v2c', //数据库默认是 v2c
      transport: 'udp',
      community: '', //SNMP v1 或 v2c 凭据：SNMP v1 或 v2c 必需。
      port: 161, //默认是161
      force_add: 1, //是否强制添加 0否 其他值为是
      disabled: 0, //0为启用 其他为禁用
      authlevel: '', //身份验证级别
      authname: '', //身份验证用户名
      authpass: '', //身份验证密码
      authalgo: '', //身份验证算法
      cryptopass: '', //加密密码
      cryptoalg: '', //加密算法
      hardware: '' //硬件
    }
  }
  formRef.value?.resetFields()
}
</script>

<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>
